import React, { Component } from 'react'
import { LoadingOutlined } from '@ant-design/icons'
import './index.css'

/**
 * @author liu_jshan
 * @version 1.1 
 * @date 2024-02-25
 */
class Button extends Component {
    constructor(props) {
        super(props)
        this.state = {
            type: 'button',
            loading: false
        }
    }

    async componentDidMount() {
        const type = this.props.type ? this.props.type : 'button'
        await new Promise(resolve => {
            this.setState({
                type
            }, resolve)
        })
    }

    render() {
        return (
            <button
                className={this.props.className ? this.props.className : 'buttonWidget'}
                style={this.props.style}
                type={this.state.type}
                disabled={this.props.disabled}
                title={this.props.title}
                onClick={async (event) => {
                    if (this.state.type === 'submit') {
                        event.preventDefault()
                    }
                    //异步防抖
                    if (this.state.loading === true) return
                    if (this.props.onClick && typeof this.props.onClick === 'function') {
                        await new Promise(resolve => {this.setState({loading: true}, resolve)})
                        await this.props.onClick(event)
                        await new Promise(resolve => {this.setState({loading: false}, resolve)})
                    }
                }}
            >
                {
                    this.state.loading === true ?
                        <LoadingOutlined style={{fontSize: '1.3em'}}/> :
                        this.props.buttonName || this.props.children
                }
            </button>
        )
    }
}

export default Button

export function TableButton(props) {
    return <Button {...props} style={{...props.style, padding: '0.5em 1em', fontSize: '0.8em', borderRadius: '2px'}}/>
}
